package com.learn.sang.xmlparser;

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

/**
 * 列出所有用户
 * 
 * @author zangweiren 2010-4-17
 * 
 */
public class ListUsers {
	// 获得解析器
	public static XMLStreamReader getStreamReader() {
		String xmlFile = ListUsers.class.getResource("/").getFile()
				+ "../resource/study_use/users.xml";
		XMLInputFactory factory = XMLInputFactory.newFactory();
		try {
			XMLStreamReader reader = factory
					.createXMLStreamReader(new FileReader(xmlFile));
			return reader;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 列出所有用户名称
	public static void listNames() {
		XMLStreamReader reader = ListUsers.getStreamReader();
		// 遍历XML文档
		try {
			while (reader.hasNext()) {
				int event = reader.next();
				// 如果是元素的开始
				if (event == XMLStreamConstants.START_ELEMENT) {
					// 列出所有用户名称
					if ("user".equalsIgnoreCase(reader.getLocalName())) {
						System.out.println("Name:"
								+ reader.getAttributeValue(null, "name"));
					}
				}
			}
			reader.close();
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		ListUsers.listNames();
	}
}